const knex = require('knex')
const moment = require('moment')
const {
  DB_HOST,
  DB_PORT,
  DB_NAME,
  DB_USER,
  DB_PASSWORD,
} = require('../../config')
const KnexService = require('./service')

const client = 'mysql2'

const connection = {
  host: DB_HOST,
  port: DB_PORT,
  database: DB_NAME,
  user: DB_USER,
  password: DB_PASSWORD,
  timezone: 'UTC',
  charset: 'utf8mb4',
  // make DATETIME column return in UTC format
  typeCast: (field, next) => {
    if (field.type === 'DATETIME') {
      const value = field.string()
      return value ? moment(value).format('YYYY-MM-DD[T]HH:mm:ss.000[Z]') : null
    }
    return next()
  },
}

const debug = false
const knexClient = knex({
  client,
  connection,
  debug,
})

// set up CRUD methods with this knex client
knexClient.service = new KnexService(knexClient)

module.exports = knexClient
